﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkitMvvmDemo.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CommunityToolkitMvvmDemo.ViewModels
{
    partial class RegisterViewModel : ObservableValidator
    {
        private string? _userName;
        [Required(ErrorMessageResourceName = "UserName_Required", ErrorMessageResourceType = typeof(Lang))]                      // 标记需要校验
        [MinLength(2, ErrorMessageResourceName = "UserName_MinLength", ErrorMessageResourceType = typeof(Lang))] // 标记需要校验
        [MaxLength(5, ErrorMessage = "最多5位")] // 标记需要校验
        public string? UserName
        {
            get => _userName;
            set
            {
                SetProperty(ref _userName, value, true);
            }
        }


        //[ObservableProperty]
        //[Required(ErrorMessage = "邮箱不能为空")]
        //[EmailAddress]
        //string? _email;

        string? _email;
        [Required(ErrorMessage = "邮箱不能为空")]
        [EmailAddress]
        public string? Email
        {
            get => _email;
            set
            {
                SetProperty(ref _email, value, true);
            }
        }


        private int? _age;
        [Required]
        [Range(10, 100)]
        public int? Age
        {
            get { return _age; }
            set
            {
                //SetProperty(ref _age2, value);
                //ValidateProperty(value); // 前端校验

                SetProperty(ref _age, value, true); // 前端校验
            }
        }

        //[ObservableProperty]
        //[Required]
        //[Range(10, 100)]
        //int? age;
        //partial void OnAgeChanged(int? value)
        //{
        //    ValidateProperty(value, nameof(Age)); // 前端校验
        //}

        [ObservableProperty]
        string? _errorMessages;

        [RelayCommand]
        void Register()
        {
            ValidateAllProperties();  // 触发校验，后端校验

            if (HasErrors)
            {
                ErrorMessages = string.Join(Environment.NewLine, GetErrors());
                return;
            }
            ErrorMessages = "";
            MessageBox.Show("Registration Successful !!!");
        }

    }
}
